<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <title>仿真创建与实时折线图展示</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; max-width: 900px; margin: auto; }
        label { display: block; margin-top: 15px; }
        input[type="text"], input[type="number"] { width: 100%; padding: 8px; margin-top: 5px; }
        button { margin-top: 15px; padding: 10px 20px; font-size: 16px; cursor: pointer; }
        #status { margin-top: 10px; color: green; }
        canvas { background: #f9f9f9; border: 1px solid #ccc; margin-top: 30px; }
    </style>
</head>
<body>
<h2>仿真结果创建与实时展示</h2>

<button id="createTotalBtn">创建新的仿真汇总记录</button>
<div id="createResult" style="margin-top:10px;"></div>

<label for="envParamIdInput">env_param_id:</label>
<input type="number" id="envParamIdInput" placeholder="env_param_id" />

<label for="simulationResultTotalIdInput">simulation_result_total_id:</label>
<input type="number" id="simulationResultTotalIdInput" placeholder="simulation_result_total_id" />

<button id="startSimulationBtn">开始仿真运行</button>

<div id="status"></div>

<canvas id="simulationChart" width="800" height="400"></canvas>

<script>
    const createTotalBtn = document.getElementById('createTotalBtn');
    const createResultDiv = document.getElementById('createResult');
    const envParamIdInput = document.getElementById('envParamIdInput');
    const simulationResultTotalIdInput = document.getElementById('simulationResultTotalIdInput');
    const startSimulationBtn = document.getElementById('startSimulationBtn');
    const statusDiv = document.getElementById('status');
    const ctx = document.getElementById('simulationChart').getContext('2d');

    let socket = null;

    const simulationChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                { label: 'Battery Energy', data: [], borderColor: 'blue', fill: false, tension: 0.1 },
                { label: 'Grid Power', data: [], borderColor: 'red', fill: false, tension: 0.1 },
                { label: 'Solar Power', data: [], borderColor: 'orange', fill: false, tension: 0.1 }
            ]
        },
        options: {
            responsive: true,
            scales: {
                x: { title: { display: true, text: '时间点' } },
                y: { title: { display: true, text: '数值' }, beginAtZero: true }
            }
        }
    });

    // 创建新的 simulation_result_total 记录
    createTotalBtn.onclick = async () => {
        const payload = {
            env_param_id: 1,  // 这里你可以改成动态值或输入框获取
            battery_energy: "0",
            solar_power: "0",
            grid_power: "0",
            wind_power: "0",
            total_power: "0",
            solar_cost: "0",
            wind_cost: "0",
            grid_cost: "0",
            solar_emission: "0",
            wind_emission: "0",
            grid_emission: "0",
            period_unit: "day",
            period: 24,
            name: "前端创建的仿真汇总"
        };

        try {
            const resp = await fetch('http://localhost:8081/simulation-result-total/', {  // 修改成你的后端接口地址
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            if (!resp.ok) throw new Error(`HTTP 错误! 状态: ${resp.status}`);

            const json = await resp.json();

            if (json.code === 200 && json.data) {
                createResultDiv.innerText = `创建成功，ID: ${json.data.simulation_result_total_id}`;
                envParamIdInput.value = json.data.env_param_id;
                simulationResultTotalIdInput.value = json.data.simulation_result_total_id;
                statusDiv.innerText = "";
            } else {
                createResultDiv.innerText = `创建失败: ${json.msg || '未知错误'}`;
            }
        } catch (err) {
            createResultDiv.innerText = `请求错误: ${err.message}`;
        }
    };

    // 开始仿真，打开 WebSocket 并监听数据
    startSimulationBtn.onclick = () => {
        const envParamId = envParamIdInput.value.trim();
        const simulationResultTotalId = simulationResultTotalIdInput.value.trim();

        if (!envParamId || !simulationResultTotalId) {
            alert('请先输入有效的 env_param_id 和 simulation_result_total_id');
            return;
        }

        if (socket && socket.readyState === WebSocket.OPEN) {
            alert('仿真已在进行中，请勿重复开始');
            return;
        }

        simulationChart.data.labels = [];
        simulationChart.data.datasets.forEach(ds => ds.data = []);
        simulationChart.update();

        statusDiv.innerText = '连接中...';

        socket = new WebSocket(`ws://localhost:8081/simulation-result-total/ws/start_simulation?env_param_id=${envParamId}&simulation_result_total_id=${simulationResultTotalId}`);

        socket.onopen = () => {
            statusDiv.innerText = 'WebSocket 连接已打开，仿真开始运行...';
        };

        socket.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.simulation_result) {
                    const sim = data.simulation_result;
                    const timeLabel = sim.time_point ? new Date(sim.time_point).toLocaleTimeString() : `Hour ${simulationChart.data.labels.length + 1}`;

                    if (!simulationChart.data.labels.includes(timeLabel)) {
                        simulationChart.data.labels.push(timeLabel);
                        simulationChart.data.datasets[0].data.push(Number(sim.battery_energy));
                        simulationChart.data.datasets[1].data.push(Number(sim.grid_power));
                        simulationChart.data.datasets[2].data.push(Number(sim.solar_power));
                        simulationChart.update();
                        console.log(sim);
                    }
                } else if (data.status === "completed") {
                    statusDiv.innerText = '仿真完成！';
                    socket.close();
                } else if (data.error) {
                    statusDiv.innerText = '错误: ' + data.error;
                }
            } catch (e) {
                console.error("解析 WebSocket 数据异常:", e);
            }
        };

        socket.onerror = (event) => {
            statusDiv.innerText = 'WebSocket 连接错误';
            console.error(event);
        };

        socket.onclose = () => {
            statusDiv.innerText += ' 连接已关闭';
        };
    };
</script>
</body>
</html>
